<template>
  <div
    v-html="displayText ?? '初始化中'"
    class="markdown-body cnblogs-markdown"
  ></div>
</template>

<script setup lang="ts">
import MarkdownIt from "markdown-it";
import "github-markdown-css/github-markdown-light.css";
import { computed, onMounted, onUnmounted } from "vue";
import hljs from "highlight.js";
import "highlight.js/styles/default.css"; // 您可以更换为其他样式
import ClipboardJS from "clipboard";

const props = defineProps({
  text: {
    type: String,
    default: "",
  },
});
let markdownItInstance: MarkdownIt = new MarkdownIt({
  highlight(value, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return `<pre class="pre-wrap hljs"><code class="hljs ${lang}">${
          hljs.highlight(value, { language: lang }).value
        }</code><span class="copy-btn">复制</span></pre>`;
      } catch (__) {}
    }
    return `<pre class="pre-wrap hljs"><code class="hljs">${
      hljs.highlightAuto(value).value
    }</code><span class="copy-btn">复制</span></pre>`;
  },
});
let clipboard: ClipboardJS;
onMounted(() => {
  clipboard = new ClipboardJS(".copy-btn", {
    target: (trigger) => {
      return trigger.parentElement?.querySelector("code") as HTMLElement;
    },
  });

  clipboard.on("success", (e) => {
    e.trigger.classList.add("copyed");
    e.trigger.innerHTML = "复制成功";
    setTimeout(() => {
      e.trigger.classList.remove("copyed");
      e.trigger.innerHTML = "复制";
    }, 2000);
    e.clearSelection();
  });

  clipboard.on("error", () => {
    console.log("复制失败，请手动复制！");
  });
});
onUnmounted(() => {
  clipboard.destroy(); // 销毁 ClipboardJS 实例以释放资源
});
const displayText = computed(() => {
  return markdownItInstance.render(props.text);
});
</script>

<style scoped></style>
